import sys
import os
import argparse
import cv2
import numpy as np
import json


def pretreatment(in_file_path, points, height, out_file_path):
    """
    图片预处理，切割并矫正
    :param in_file_path: 图片路径
    :param points: 图片切割点位，人工通过摄像头截图截图点位集合，格式示例：[[0,330],[2100,210],[0,1390],[2560,920]]
    :param height: 输出图片高度
    :param out_file_path: 文件处理后输出路径，可为空
    :return:
    """
    img = cv2.imread(in_file_path)
    h_max,l_max = img.shape[:2]
    # 根据实际情况计算得出的高度
    h_max = height
    # original pts
    json_list = json.loads(points)
    num_points = list(json_list)
    pts_o = np.float32(num_points)  # 这四个点为原始图片上数独的位置
    # 长,高
    pts_d = np.float32([[0, 0], [l_max, 0], [0, h_max], [l_max, h_max]])  # 这是变换之后的图上四个点的位置
    # get transform matrix
    M = cv2.getPerspectiveTransform(pts_o, pts_d)
    # apply transformation
    dst = cv2.warpPerspective(img, M, (l_max, h_max))  # 最后一参数是输出dst的尺寸。可以和原来图片尺寸不一致。按需求来确定
    cv2.imwrite(out_file_path, dst)
    print(f"Successfully executed")

if __name__ == '__main__':
    # 创建一个参数解析实例
    parser = argparse.ArgumentParser(description='Process some integers.')

    # 添加参数解析
    parser.add_argument('-i', '--input', type=str, help='-i is input file path')
    parser.add_argument('-s', '--points', type=str, help='-s is point list')
    parser.add_argument('-x', '--height', type=str, help='-x is the height of the output image')
    parser.add_argument('-o', '--output', type=str, help='-o is output file path')
    args = parser.parse_args()
    if args.input is None:
        print("-i is not None")
        sys.exit()
    if args.points is None:
        print("-s is not None")
        sys.exit()
    if args.height is None:
        print("-x is not None")
        sys.exit()
    if args.output is None:
        filename = os.path.splitext(args.input)[0]  # 文件名
        filetype = os.path.splitext(args.input)[1]  # 文件扩展名
        args.o = filename + '/handle' + filetype
    # 输入参数
    # print(f"--i: {args.input}")
    # print(f"--s: {args.points}")
    # print(f"--x: {args.height}")
    # print(f"--o: {args.output}")
    pretreatment(args.input, args.points, int(args.height), args.output)
